#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class PurchaseCloseReason(models.TransientModel):
    _name = 'purchase.close.reason.wizard'
    _description = 'Purchase Close Reason Wizard'

    close_reason = fields.Text(string='关闭原因', required=True)
    pur_req_id = fields.Many2one('purchase.requisition', string='请购单', required=False)
    pur_req_line_id = fields.Many2one('purchase.requisition.line', string='请购单明细', required=False)
    to_state = fields.Char('To State')

    def action_confirm(self):
        self.ensure_one()
        # 将原因记录到采购订单的备注中
        if self.pur_req_id:
            for row in self.with_context({
                'skip_pur_close_reason': True
            }).pur_req_id.pr_line_ids.filtered(lambda x: x.product_qty != x.qty_received):
                row.action_done()
            # self.pur_req_id.state = self.to_state
            self.pur_req_id.message_post(body=f'关闭原因：{self.close_reason}')
            self.pur_req_id.update_state()
            self.pur_req_id.sb_workflow_item_ids.filtered(lambda x: x.state in ['wait_forward', 'approval']).unlink()
        elif self.pur_req_line_id:
            self.pur_req_line_id.state = self.to_state
            self.pur_req_line_id.requisition_id.message_post(body=f'关闭原因：{self.close_reason}')
            self.pur_req_line_id.requisition_id.update_state()
            self.pur_req_line_id.requisition_id.sb_workflow_item_ids.filtered(
                lambda x: x.state in ['wait_forward', 'approval']).unlink()
        return {'type': 'ir.actions.act_window_close'}

    def action_confirm_close(self):
        requisition_id = self.pur_req_id
        requisition_id.state = 'closed'
        # 未处理完成的需要关闭
        requisition_id.pr_line_ids.filtered(lambda x: x.product_qty != x.qty_received).update({'state': 'closed'})
        # 删除审批记录
        # requisition_id.sb_workflow_item_ids.unlink()
        # requisition_id.sb_workflow_id = False
        # 将当前审批拒绝, 删除剩余审批
        requisition_id.sb_workflow_item_ids.filtered(lambda x: x.state == 'approval').reject_approve()
        requisition_id.sb_workflow_item_ids.filtered(lambda x: x.state in ['wait_forward', 'approval']).unlink()
        requisition_id.close_remark = self.close_reason
        requisition_id.message_post(body=f'Close Reason：{self.close_reason}')
